package com.solar.etl.transform;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import org.dom4j.Element;

import com.solar.etl.config.mapping.Field;
import com.solar.etl.spi.Itransform;

public class Hash32 implements Itransform{
	String str;
	public String md5s(String plainText) {  
		try {   
			MessageDigest md = MessageDigest.getInstance("MD5");   
			md.update(plainText.getBytes());   
			byte b[] = md.digest();   
			int i;   
			StringBuffer buf = new StringBuffer("");   
			for (int offset = 0; offset < b.length; offset++) {    
				i = b[offset];    
				if (i < 0)     i += 256;    
				if (i < 16)     buf.append("0");    
				buf.append(Integer.toHexString(i));   
			}   
			str = buf.toString();
			return buf.toString();
				
			} catch (NoSuchAlgorithmException e) {   
				// TODO Auto-generated catch block   
				e.printStackTrace();  
				return null;
			} 
		}

	@Override
	public String transform(Field field, Element item) {
		String value="";
		String val=field.destValue;
		if (val==null) return null;
		String[] vals =((String)val).split(",");
		for (int i = 0; i < vals.length; i++) {
			vals[i] = vals[i].trim();
		}
		Arrays.sort(vals);  
		for (int i = 0; i < vals.length; i++) {
			if(vals[i]!=null && !vals[i].trim().equals("")){
				value+=vals[i].trim().toUpperCase()+",";
			}
		} 
		if(value.equals("")){
			field.destValue="";
		}else{
			field.destValue= md5s(value);
		}
		return null;
	} 
}
